package com.nuoniu.sibanyun.controller.crm.call;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nuoniu.sibanyun.common.BaseController;
import com.nuoniu.sibanyun.common.io.IOUtils;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.entity.crm.call.CrmCallTask;
import com.nuoniu.sibanyun.entity.crm.call.CrmCallTaskRecord;
import com.nuoniu.sibanyun.entity.crm.call.dto.CrmCallTaskDto;
import com.nuoniu.sibanyun.entity.crm.call.dto.CrmCallTaskRecordCallBackDto;
import com.nuoniu.sibanyun.entity.crm.call.dto.CrmCallTaskRecordSearchDto;
import com.nuoniu.sibanyun.entity.crm.call.dto.xiangyun.CallBackRecord;
import com.nuoniu.sibanyun.entity.crm.call.rongying.*;
import com.nuoniu.sibanyun.entity.crm.call.vo.XiangYunResult;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallTaskRecordService;
import com.nuoniu.sibanyun.service.crm.call.callbackLine.impl.CallbackLineServiceImpl;
import com.nuoniu.sibanyun.utils.IpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 客户管理-外呼管理-外呼记录 前端控制器
 * </p>
 *
 * @author 白强
 * @since 2022-02-28
 */
@RestController
@RequestMapping("/crm/callTaskRecord")
@Api(tags = "客户管理-外呼管理-外呼记录")
@Log4j2
public class CrmCallTaskRecordController extends BaseController {

    @Autowired
    private ICrmCallTaskRecordService callTaskRecordService;
    @Autowired
    private CallbackLineServiceImpl callbackLineService;

    @PostMapping("pageList")
    @ApiOperation(value = "分页查询 记录")
    public HttpResult pageList(@RequestBody CrmCallTaskRecordSearchDto recordSearchDto) {
        return HttpResult.ok(callTaskRecordService.pageList(recordSearchDto));
    }


    @PostMapping("addCallBackInfo")
    @ApiOperation(value = "更新 通话记录 回调信息")
    public String addCallBackInfo(HttpServletRequest request){
        try {
            String callBackJson = IOUtils.toString(request.getInputStream(),"utf8");
            if(StringUtils.isNotBlank(callBackJson)){
                //去掉问号
                callBackJson = StringUtils.replace(callBackJson,"?","");
                log.debug("接收到 语音盒子 回调信息解析JSON;{}",callBackJson);
                CrmCallTaskRecordCallBackDto crmCallTaskRecordCallBackDto = JSON.parseObject(callBackJson, CrmCallTaskRecordCallBackDto.class);
                callTaskRecordService.addCallBackInfo(crmCallTaskRecordCallBackDto);
            }

        } catch (IOException e) {
            log.info("更新 通话记录 回调信息 异常");
            e.printStackTrace();
            return "";
        }
        return"true";
    }

    @PostMapping("callBackRecordFromXiangYun")
    @ApiOperation(value = "通话记录推送（祥云）")
    public XiangYunResult callBackRecordFromXiangYun(HttpServletRequest request){
        try {
            String clientIp = IpUtil.getClientIp(request);
            String callBackJson = IOUtils.toString(request.getInputStream(),"utf8");
            log.info("通话记录推送_IP:{},话单数据：{}",clientIp,callBackJson);
            CallBackRecord callBackRecord = JSON.parseObject(callBackJson, CallBackRecord.class);
            callTaskRecordService.callBackRecordFromXiangYun(callBackRecord);
        }catch (Exception e){
            return XiangYunResult.error(500,e.getMessage());
        }
        return XiangYunResult.ok("操作成功");
    }


    @PostMapping("uploadAudio")
    @ApiOperation(value = "上传 通话语音")
    public String uploadAudio(HttpServletRequest request,String callId, String pid, String IMEI){
        try {
            callTaskRecordService.uploadAudio(request, callId, pid, IMEI);
        } catch (Exception e) {
            log.info("上传 通话语音 异常");
            e.printStackTrace();
            return "";
        }
        return "true";
    }

    @PostMapping("callBackRecordFromRongYing")
    @ApiOperation(value = "通话记录推送(融营)")
    public RongYingResult recordCallBack(@RequestBody RongYingCallBack rongYingCallBack){
        log.info("融营 话单推送：{}",JSON.toJSONString(rongYingCallBack));
        callbackLineService.recordCallBack(rongYingCallBack);
        log.info("融营 推送成功 ");
        return RongYingResult.ok("推送成功");
    }

    @PostMapping("listenerStateFromRongYing")
    @ApiOperation(value = "拨打状态监听(融营)")
    public void recordCallBack(@RequestBody RongYingCallState rongYingCallState){
        callbackLineService.listenerState(rongYingCallState);
    }


    @PostMapping("call")
    @ApiOperation(value = "呼出")
    public RongYingCallResult call(@RequestBody CallMode callMode){
        return callbackLineService.call(callMode);
    }

    @PostMapping("hangUp")
    @ApiOperation(value = "终止呼叫")
    public RongYingCallResult hangUp(String SessionId){
        return callbackLineService.hangUp(SessionId);
    }

}
